package com.tn.service.dwr;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;

import com.googlecode.objectify.Objectify;
import com.tn.bo.Address;
import com.tn.bo.CommunicationPreference;
import com.tn.bo.Company;
import com.tn.bo.UserGroup;
import com.tn.bo.UserProfile;
import com.tn.bo.UserProfileCurrentProperties;
import com.tn.bo.UserPropsTransfer;
import com.tn.dao.CompanyDAO;
import com.tn.dao.NotificationsDAO;
import com.tn.dao.ObjectifyGenericDao;
import com.tn.dao.UserDAO;
import com.tn.util.MailService;
import com.tn.xfer.DwrResponse;

public class UserManagementDwr {
	public DwrResponse addUpdateDeleteLocation(Address address, String companyId, boolean deleteFlag){
		DwrResponse resp = new DwrResponse("ADDUPD_LOCATION", 0);
		try{
			CompanyDAO cdao = new CompanyDAO();
			Company company = cdao.findCompanyByCompanyId(companyId);
			if(company != null){
				if(company.getLocations() == null){
					company.setLocations(new ArrayList<Address>());
				}
				if(StringUtils.isNotEmpty(address.getLocationId())){
					for(Address a: company.getLocations()){
						if(address.getLocationId().equals(a.getLocationId())){
							if(deleteFlag){
								company.getLocations().remove(a);
							}else{
								company.getLocations().remove(a);
								company.getLocations().add(address);
							}
							break;
						}
					}
				}else{
					address.setLocationId(String.valueOf(System.currentTimeMillis()));
					company.getLocations().add(address);
				}
				
				cdao.insertCompany(company);
				resp.setObjRespOrError(company);
				//deleteAllLocations(company);
			}else{
				resp.setObjRespOrError(null);
				resp.setRespCode(-1);
			}
		}catch(Exception ex){
			resp.setObjRespOrError(ex);
			resp.setRespCode(-1);
		}
		
		return resp;
	}
	
	public DwrResponse updatePaymentInformation(List<String> pmtTerms, String scheduleType, String scheduleValue, String companyId){
		DwrResponse resp = new DwrResponse("ADDUPD_PAYMENTTERMS", 0);
		try{
			CompanyDAO cdao = new CompanyDAO();
			Company company = cdao.findCompanyByCompanyId(companyId);
			if(company != null){
				company.setPaymentTerms(pmtTerms);
				company.setPaymentScheduleType(scheduleType);
				company.setPaymentScheduleValue(scheduleValue);
				cdao.insertCompany(company);
			}
		}catch(Exception ex){
			resp.setObjRespOrError(ex);
			resp.setRespCode(-1);
		}
		
		return resp;
	}
	
	/*public DwrResponse addUpdateDeletePaymentTerms(PaymentTerms paymentTerms, String companyId, boolean deleteFlag){
		DwrResponse resp = new DwrResponse("ADDUPD_PAYMENTTERMS", 0);
		try{
			CompanyDAO cdao = new CompanyDAO();
			Company company = cdao.findCompanyByCompanyId(companyId);
			if(company != null){
				if(company.getPaymentTerms() == null){
					company.setPaymentTerms(new ArrayList<PaymentTerms>());
				}
				if(StringUtils.isNotEmpty(paymentTerms.getId())){
					for(PaymentTerms a: company.getPaymentTerms()){
						if(paymentTerms.getId().equals(a.getId())){
							if(deleteFlag){
								company.getPaymentTerms().remove(a);
							}else{
								company.getPaymentTerms().remove(a);
								company.getPaymentTerms().add(paymentTerms);
							}
							break;
						}
					}
				}else{
					paymentTerms.setId(String.valueOf(System.currentTimeMillis()));
					company.getPaymentTerms().add(paymentTerms);
				}
				
				cdao.insertCompany(company);
				resp.setObjRespOrError(company);
				//deleteAllLocations(company);
			}else{
				resp.setObjRespOrError(null);
				resp.setRespCode(-1);
			}
		}catch(Exception ex){
			resp.setObjRespOrError(ex);
			resp.setRespCode(-1);
		}
		
		return resp;
	}*/
	
	/*public void deleteAllLocations(Company c){
		CompanyDAO cd = new CompanyDAO();
		c.setLocations(null);
		cd.insertCompany(c);
	}*/
	
	
	public DwrResponse getUserProifileByCompany(String companyId){
		DwrResponse resp = new DwrResponse("GET_USER_PROFILE_BY_COMPANY", 0);
		try{
			UserDAO uDao = new UserDAO();
			ArrayList<UserPropsTransfer> userPropsList = new ArrayList<UserPropsTransfer>();
			ArrayList<UserProfile> list = uDao.getByProperty("companyId", companyId);
			if(list != null && list.size() > 0){
				for(UserProfile userProfile: list){
					UserPropsTransfer xfer = new UserPropsTransfer();
					xfer.setCompanyId(companyId);
					xfer.setUserProfileId(userProfile.getUserProfileId());
					xfer.setFirstName(userProfile.getFirstName());
					xfer.setLastName(userProfile.getLastName());
					xfer.setEmailAddress(userProfile.getEmailAddress());
					if("true".equalsIgnoreCase(userProfile.getIsVerified())){
						xfer.setVerified(true);
					}else{
						xfer.setVerified(false);
					}
					
					xfer.setUserGroupId(userProfile.getUserGroupId());
					xfer.setDisabled(userProfile.isDisabled());
					
					if(userProfile.getCurrentProperties() == null){
						xfer.setCancelPO(false);
						xfer.setChangePO(false);
						xfer.setCreateInvoices(false);
						xfer.setCreatePO(false);
						xfer.setPostPayments(false);
						xfer.setRestrictByDocNumber(false);
						xfer.setSuperUser(false);
						xfer.setUserPropsId(null);
					}else{
						xfer.setSuperUser(userProfile.getCurrentProperties().isSuperUser());
						if(userProfile.getCurrentProperties().isSuperUser()){
							xfer.setVerified(true);
						}
						xfer.setCancelPO(userProfile.getCurrentProperties().isCancelPO());
						xfer.setChangePO(userProfile.getCurrentProperties().isChangePO());
						xfer.setCreateInvoices(userProfile.getCurrentProperties().isCreateInvoices());
						xfer.setCreatePO(userProfile.getCurrentProperties().isCreatePO());
						xfer.setPostPayments(userProfile.getCurrentProperties().isPostPayments());
						xfer.setRestrictByDocNumber(userProfile.getCurrentProperties().isRestrictByDocNumber());
						xfer.setUserPropsId(userProfile.getCurrentProperties().getId());
					}
					
					userPropsList.add(xfer);
				}
			}
			resp.setObjRespOrError(userPropsList);
		}catch(Exception ex){
			resp.setObjRespOrError(ex);
			resp.setRespCode(-1);
		}
		
		return resp;
	}
	
	public DwrResponse updateUserProperties(List<UserPropsTransfer> updList){
		DwrResponse resp = new DwrResponse("UPD_USER_PROPS", 0);
		try{
			UserDAO uDao = new UserDAO();
			if(updList != null && updList.size() > 0){
				for(UserPropsTransfer uProps: updList){
					
					UserProfile userProfile = uDao.getUserProfile(uProps.getUserProfileId());
					
					if(uProps.isVerified() && !uProps.isSuperUser() ){
						userProfile.setIsVerified("true");
						//Send Approval Mail for user.
						MailService ms = new MailService();
						ms.sendApprovedMail(userProfile);
					}

					if(userProfile.getCurrentProperties() == null){
						userProfile.setCurrentProperties(new UserProfileCurrentProperties());
						userProfile.getCurrentProperties().setId(userProfile.getUserProfileId() + "|" + uProps.getCompanyId() + "|" + String.valueOf(Math.round(Math.random()*1000)));
					}else{
						userProfile.getCurrentProperties().setId(uProps.getUserPropsId());
					}
					
					userProfile.getCurrentProperties().setSuperUser(uProps.isSuperUser());
					userProfile.getCurrentProperties().setCancelPO(uProps.isCancelPO());
					userProfile.getCurrentProperties().setChangePO(uProps.isChangePO());
					userProfile.getCurrentProperties().setCreateInvoices(uProps.isCreateInvoices());
					userProfile.getCurrentProperties().setCreatePO(uProps.isCreatePO());
					userProfile.getCurrentProperties().setPostPayments(uProps.isPostPayments());
					userProfile.getCurrentProperties().setRestrictByDocNumber(uProps.isRestrictByDocNumber());
					uDao.updateUser(userProfile);
				}
			}
		
		}catch(Exception ex){
			resp.setObjRespOrError(ex);
			resp.setRespCode(-1);
		}
		
		return resp;
	}
	
	public DwrResponse getNotificationsForUser(String companyId, Date lastLoginTime, boolean isBuyer){
		DwrResponse resp = new DwrResponse("UPD_USER_PROPS", 0);
		try{
			CompanyDAO cDao = new CompanyDAO();
			NotificationsDAO nDao = new NotificationsDAO();
			Company c = cDao.findCompanyByCompanyId(companyId);
			Map<String, String> notifications = nDao.getNotificatinsForUser(c, lastLoginTime, isBuyer);
			resp.setObjRespOrError(notifications);
		}catch(Exception ex){
			resp.setObjRespOrError(ex);
			resp.setRespCode(-1);
		}
		
		return resp;
	}
	
	
	public DwrResponse updateCommunicationPrefs(CommunicationPreference prefs, String companyId){
		DwrResponse resp = new DwrResponse("UPD_USER_PROPS", 0);
		try{
			CompanyDAO cDao = new CompanyDAO();
			
			Company c = cDao.findCompanyByCompanyId(companyId);
			
			if(c != null){
				c.setEmailPreferences(prefs);
				c = cDao.insertCompany(c);
			}
			
			resp.setObjRespOrError(c);
		}catch(Exception ex){
			resp.setObjRespOrError(ex);
			resp.setRespCode(-1);
		}
		
		return resp;
	}
	
	public DwrResponse createOrSaveUserGroup(UserGroup ug, boolean isCreate){
		DwrResponse response = new DwrResponse("CREATE_SAVE_UG", 0);
		try{
			ObjectifyGenericDao<UserGroup> basicUserDao = new ObjectifyGenericDao<UserGroup>(UserGroup.class);
			basicUserDao.put(ug);
			response = getUserGroupList(ug.getCompanyId());
		}catch(Exception ex){
			ex.printStackTrace();
			response.setObjRespOrError(ex);
			response.setRespCode(-1);
		}
		
		return response;
	}
	
	public DwrResponse getUserGroupList(String propValue){
		DwrResponse response = new DwrResponse("CREATE_SAVE_UG", 0);
		try{
			ObjectifyGenericDao<UserGroup> basicUserDao = new ObjectifyGenericDao<UserGroup>(UserGroup.class);
			List<UserGroup> listUG =  basicUserDao.listByProperty("companyId", propValue);
			response.setObjRespOrError(listUG);
		}catch(Exception ex){
			ex.printStackTrace();
			response.setObjRespOrError(ex);
			response.setRespCode(-1);
		}
		
		return response;
	}
	
	
	public DwrResponse updateUserProfileGroup(Long userProfileId, String groupId, String companyId){
		DwrResponse response = new DwrResponse("Update_UPG", 0);
		try{
			ObjectifyGenericDao<UserProfile> basicUserDao = new ObjectifyGenericDao<UserProfile>(UserProfile.class);
			UserProfile profile = basicUserDao.get(userProfileId);
			if(profile != null){
				profile.setUserGroupId(groupId);
				Objectify tx = basicUserDao.beginTransaction();
				basicUserDao.put(profile);
				basicUserDao.commitTransaction(tx);
			}
			response.setObjRespOrError(getUserProifileByCompany(companyId));
		}catch(Exception ex){
			ex.printStackTrace();
			response.setObjRespOrError(ex);
			response.setRespCode(-1);
		}
		
		return response;
	}
	
	public DwrResponse updateUserPropertyAsString(Long userProfileId, String propertyName, String newValue, String companyId){
		DwrResponse response = new DwrResponse("Update_UPG", 0);
		try{
			ObjectifyGenericDao<UserProfile> basicUserDao = new ObjectifyGenericDao<UserProfile>(UserProfile.class);
			UserProfile profile = basicUserDao.get(userProfileId);
			if(profile != null){
				if("VERIFY".equals(propertyName)){
					profile.setIsVerified(newValue);
				}else if("DISABLE".equals(propertyName)){
					if("true".equals(newValue)){
						profile.setDisabled(true);
					}else{
						profile.setDisabled(false);
					}
				}
				Objectify tx = basicUserDao.beginTransaction();
				basicUserDao.put(profile);
				basicUserDao.commitTransaction(tx);
			}
			response.setObjRespOrError(getUserProifileByCompany(companyId));
		}catch(Exception ex){
			ex.printStackTrace();
			response.setObjRespOrError(ex);
			response.setRespCode(-1);
		}
		
		return response;
	}
}
